package com.imooc.exceptions;

import com.imooc.grace.result.GraceJSONResult;
import com.imooc.grace.result.ResponseStatusEnum;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version 1.0
 * @Author Mr.Yang
 * @Date 2024-08-05 20:26
 * @question: 自定义异常捕获器
 */

@ControllerAdvice
public class GraceExceptionHandler {

    /**
     * 文件上传超过多大(如设置的700)异常
     * @param e
     * @return
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseBody
    public GraceJSONResult returnMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
        //异常输出
        e.printStackTrace();
        return GraceJSONResult.exception(ResponseStatusEnum.FILE_MAX_SIZE_700KB_ERROR);
    }

    /**
     * 除0异常
     * @param e
     * @return
     */
    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public GraceJSONResult returnArithmeticException(ArithmeticException e) {
        //异常输出
        e.printStackTrace();
        return GraceJSONResult.errorMsg(e.getMessage());
    }

    @ExceptionHandler(MyCustomException.class)
    @ResponseBody
    public GraceJSONResult returnMyCustomException(MyCustomException e) {
        //异常输出
        e.printStackTrace();
        return GraceJSONResult.exception(e.getResponseStatusEnum());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public GraceJSONResult returnNotValidException(MethodArgumentNotValidException e) {
        //异常输出
        e.printStackTrace();
        BindingResult result = e.getBindingResult();
        Map<String, String> errorsMap = getErrors(result);
        return GraceJSONResult.errorMap(errorsMap);
    }

    /**
     * 构建返回Map
     * @param bindingResult
     * @return
     */
    public Map<String, String> getErrors(BindingResult bindingResult) {
        Map<String, String> map = new HashMap<>();

        List<FieldError> fieldErrorList = bindingResult.getFieldErrors();
        for (FieldError fieldError : fieldErrorList) {
            //错误所对应的属性字段名
            String field = fieldError.getField();
            //错误信息
            String message = fieldError.getDefaultMessage();
            map.put(field, message);
        }
        return map;
    }

}
